package org.example.network.demo4;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.SneakyThrows;
import org.example.network.demo2.server.ServerInboundHandler;

/**
 * @author Gong.Yang
 * 演示LengthFieldBasedFrameDecoder和LengthFieldPrepender
 */
public class Server {
    private final static ChannelHandler[] shardOut = new ChannelHandler[]{
            new LengthFieldPrepender(4)
    };

    private final static ChannelHandler[] shardIn = new ChannelHandler[]{

    };

    @SneakyThrows
    public static void main(String[] args) {
        NioEventLoopGroup parent = new NioEventLoopGroup(1);
        NioEventLoopGroup child = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(parent, child)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        //出站
                        pipeline.addLast(shardOut);

                        //入站
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));//粘包半包解决
                        pipeline.addLast(new ServerInboundHandler());//输出数据

                    }
                });

        ChannelFuture future = serverBootstrap.bind(8848).sync(); //阻塞到完成端口绑定
        future.channel().closeFuture().sync();  //阻塞到绑定的NioServerSocketChannel关闭
    }
}
